#include "uni_hal_ssp_play.h"
#include "uni_iot.h"
#include "dma.h"
#include "ssp.h"
#include "rtthread.h"
#include "DrvUART010.h"
#include "gpio.h"
#include "uni_hal_audio_buf.h"

#define SSP_DAC_PRINT(format, ...)  		rt_kprintf("%s %d:"format, __FUNCTION__, __LINE__, ##__VA_ARGS__)

#define SSP_AUDIO_BUF_SIZE        (512)
#define SSP_PA_EN_GPIO 						31//power amplifier enable pin

#define SSP_PLAY_DMA_CH 					1
#define SSP_PLAY_DMA_REQ 					0

static AudioBufHandler g_audio_buf_handler = NULL;

static void _inject_audio_data(void) {
  const char *audio_buf = NULL;
  int size = 0;
  audio_buf = uni_audio_buf_read(g_audio_buf_handler, &size);
  if (audio_buf && (size > 0)) {
	fLib_SetSSP_DMA(SSP_FTSSP010_0_PA_BASE, 1, 0);
    fLib_DMA0(SSP_FTSSP010_0_PA_BASE + SSP_DATA, 
              (UINT32)audio_buf, size, SSP_PLAY_DMA_CH,
              SSP_PLAY_DMA_REQ, RAM2FIFO);
  }
}

static void ssp_play_cb(dma_event_t event, void *user_data) {
  if( event != DMA_EVENT_TC ){
    fLib_printf("DMA error occurred!\r\n");
    return;
  }
  fLib_SetSSP_DMA(SSP_FTSSP010_0_PA_BASE, 0, 0);
  _inject_audio_data();
}

int uni_hal_ssp_dac_init(void) {
  if (NULL == g_audio_buf_handler) {
    g_audio_buf_handler = uni_audio_buf_create(SSP_AUDIO_BUF_SIZE);
    if (g_audio_buf_handler) {
      fLib_DMARegisterCallback(SSP_PLAY_DMA_CH, ssp_play_cb,NULL);
      ssp_play_init();
      uni_set_gpio_dir(SSP_PA_EN_GPIO, 1);
      _inject_audio_data();
    }
  }
  return 0;
}

void uni_hal_ssp_dac_play(unsigned char *buf, unsigned int buf_size) {
  uni_audio_buf_write(g_audio_buf_handler, (char *)buf, (int)buf_size);
}

void uni_hal_ssp_play_mute(void) {
  uni_set_gpio_value(SSP_PA_EN_GPIO, 1);
}

void uni_hal_ssp_play_unmute(void) {
  uni_set_gpio_value(SSP_PA_EN_GPIO, 0);
  /*FIXME: should wait 90ms for pa unmute done*/
  uni_msleep(90);
}

